import api from '../../utils/api'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const moment = require('../../utils/moment.min.js');
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    clock:'',
    chuye:'',
    number1:'',
    bed_number:'',
    radio: '',
    chuhan:'',
    qiguan:'',
    shaoshang:'',
    show: false,
    columns: [],
    xzarr: [],
    isFocus: false,
    number: '',
    select3: '',
    select4: '',
    select5: '',
    select6: '',
    select7: '',
    select8: '',
    select9: '',
    select10: '',
    mainActiveIndex: 0,
    items: [{
        text: '主食'
      },
      {
        text: '配菜'
      },
      {
        text: '水果'
      },
      // { text: '零食' }
    ],
    select1: 'food',
    select2: 'ytshiwu',
    select: 'chuye',
    inputNumCount: '',
    outNumCount: '',
    inputNum: '',
    outNum: '',
    list: [], //记录列表
    typelist: [{
        id: 0,
        typename: '大便',
        image: '../../images/icon/db.png',
        typeIcon: '../../images/icon/db_wxz.png',
        selected: true
      },
      {
        id: 1,
        typename: '尿',
        image: '../../images/icon/n.png',
        typeIcon: '../../images/icon/n_wxz.png',
        selected: false
      },
      {
        id: 2,
        typename: '呕吐',
        image: '../../images/icon/ot.png',
        typeIcon: '../../images/icon/ot_wxz.png',
        selected: false
      },
      {
        id: 3,
        typename: '引流',
        image: '../../images/icon/yl.png',
        typeIcon: '../../images/icon/yl_wxz.png',
        selected: false
      }
    ],
    typelist1: [{
        id: '西瓜',
        image: '../../images/map/act32.png'
      },
      {
        id: '梨子',
        image: '../../images/map/act32.png'
      },
      {
        id: '甜瓜',
        image: '../../images/map/act32.png'
      },
      {
        id: '葡萄',
        image: '../../images/map/act32.png'
      },
      {
        id: '西红柿',
        image: '../../images/map/act32.png'
      },
      {
        id: '桃子',
        image: '../../images/map/act32.png'
      },
      {
        id: '樱桃',
        image: '../../images/map/act32.png'
      },
      {
        id: '香蕉',
        image: '../../images/map/act32.png'
      },
      {
        id: '黄瓜',
        image: '../../images/map/act32.png'
      },
      {
        id: '橘子',
        image: '../../images/map/act32.png'
      },
      {
        id: '苹果',
        image: '../../images/map/act32.png'
      },
      {
        id: '菠萝',
        image: '../../images/map/act32.png'
      },
    ],
    typelist2: [{
        kuai1: '吃了一大半',
        g: '≈100g'
      },
      {
        kuai1: '吃了一整个',
        g: '≈150g'
      }, {
        kuai1: '吃了2、3个',
        g: '≈300g'
      },
    ],
    typeNumlist: [{
        id: 0,
        name: '正常量',
        rank: '150-349g',
        selected: true
      },
      {
        id: 1,
        name: '量大',
        rank: '350-2000g',
        selected: false
      },
      {
        id: 2,
        name: '量少',
        rank: '50 -159g',
        selected: false
      },
      {
        id: 3,
        name: '稀便',
        rank: '50g以下',
        selected: false
      }
    ],
    popShow: false,

    //时间选择器
    topTimeShow: false,
    currentDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    topTime: '2021年2月28日',

    popClass: 1, //1 出液 2入液
    popDate: '', //日期
    popTime: '', //时间
    popMl: '', //毫升
    popType: 0, //
    popRank: 0,

    xuanze: '',
    xuanze1: '',
    xuanze2: '',
    xuanze3: '',
    typelist3: [],
    typelist4: [],
    typelist5: [],
    value: '',
    userInfo:wx.getStorageSync("userInfo")
  },



  onChange5(event) {
    console.log(event,'123456')
    if(event.detail==1){
      this.setData({
        sex:event.detail-1
      })
    }else{
      this.setData({
        sex:event.detail-1
      })
    }
    this.setData({
      radio: event.detail,
    });
  },
  onChange4(event) {
    // console.log(event,'123')
    if(event.detail==1){
      this.setData({
        sweat:event.detail
      })
    }else if(event.detail==2){
      this.setData({
        sweat:event.detail
      })
    }else if(event.detail==3){
      this.setData({
        sweat:event.detail
      })
    }else{
      this.setData({
        sweat:event.detail
      })
    }
    this.setData({
      chuhan: event.detail,
    });
  },
  onChange2(event) {
    // console.log(event,'123')
    if(event.detail==1){
      this.setData({
        cut:event.detail-1
      })
    }else{
      this.setData({
        cut:event.detail-1
      })
    }
    this.setData({
      qiguan: event.detail,
    });
  },
  onChange3(event) {
    // console.log(event,'123')
    if(event.detail==1){
      this.setData({
        burn:event.detail-1
      })
    }else{
      this.setData({
        burn:event.detail-1
      })
    }
    this.setData({
      shaoshang:event.detail,
    });
  },

  baocun(){
    this.setData({ show: false });
    this.question_list()
   
    // // 订阅信息
    // wx.requestSubscribeMessage({
    //   tmplIds: ['SJHxKzkNdFRt-OWVypXNzLxO6w6Oyz7QrLRiF_pgdrM'],
    //   success (res) {
    //     wx.request({
    //       url: 'https://server.ifufan.com/Index/wechat_auth /sendMessage',
    //       data:{
    //         userid:wx.getStorageSync("userInfo"),
    //         type:1
    //       }
    //     })
    //   }
    // })
  },

//患者第一次进入问卷
showPopup() {
  // this.setData({ show: false });
},

onClickHide() {
  // this.setData({ show: false });
},
// noop() {},

  onChangeYear(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    // let arr=[];
    // Toast(`当前值：${value}, 当前索引：${index}`);
    Toast(`当前值：${value}`);
    console.log(value);
    this.setData({
      popMl1: value,
      // columns:arr
    })

  },
  click1(event) {
    let name = event.currentTarget.dataset.num
    // console.log(name,'名字');
    var zhi;
    if (name == '正常量') {
      zhi = '150'
    } else if (name == '量大') {
      zhi = '350'
    } else if (name == '量少') {
      zhi = '50'
    } else {
      zhi = '50以下'
    }
    this.setData({
      popMl: zhi
    })
  },
  ytshiwu(e) {
    this.setData({
      popMl1: '',
      isFocus: true,
      select2: e.currentTarget.dataset.index
    })
  },
  end() {
    // console.log('点了昂');
    // let index=e.currentTarget.dataset.index
    // console.log(index);
    let arr = this.data.xzarr
    var num = 0
    let that = this
    for (let i = 0; i < arr.length; i++) {
      let data = {}
      data['food_attribute_id'] = arr[i]
      wx.request({
        url: 'https://server.ifufan.com//Index/Liquid/count_food_water',
        method: 'POST',
        data: {
          food_attribute_id: arr[i]
        },
        success(res) {
          num += parseInt(res.data.data.num)
          if (i == (arr.length - 1)) {
            that.setData({
              select1: false,
              popMl1: num
            })
          }
        }
      })
    }
  },
  hover(event) {
    let e = event.currentTarget.dataset.num
    this.setData({
      select3: e.id,
      xuanze: e.name,
      typelist2: e.attribute,
    })
  },
  hover1(event1) {
    let e = event1.currentTarget.dataset.num
    this.setData({
      select4: e.id,
      xuanze1: e.name,
      typelist3: e.attribute,
    })
  },
  hover2(event2) {
    let e = event2.currentTarget.dataset.num
    this.setData({
      select5: e.id,
      xuanze2: e.name,
      typelist4: e.attribute,
    })
  },
  hover3(event3) {
    let e = event3.currentTarget.dataset.num
    this.setData({
      select6: e.id,
      xuanze3: e.name,
      typelist5: e.attribute,
    })
  },
  hover4(event4) {
    let e = event4.currentTarget.dataset.number
    var arr = this.data.xzarr
    arr[0] = e.id
    this.setData({
      select7: e.id,
      zhiliang: e.detail,
      xzarr: arr
    })
  },
  hover5(event5) {
    let e = event5.currentTarget.dataset.number
    var arr = this.data.xzarr
    arr[1] = e.id
    console.log(e);
    this.setData({
      select8: e.id,
      zhiliang1: e.detail,
      xzarr: arr
    })
  },
  hover6(event6) {
    let e = event6.currentTarget.dataset.number
    var arr = this.data.xzarr
    arr[2] = e.id
    console.log(e);
    this.setData({
      select9: e.id,
      zhiliang2: e.detail,
      xzarr: arr
    })
  },
  hover7(event7) {
    let e = event7.currentTarget.dataset.number
    var arr = this.data.xzarr
    arr[3] = e.id
    this.setData({
      select10: e.id,
      zhiliang3: e.detail,
      xzarr: arr
    })
  },
  onClickNav(event) {
    // console.log(this.data.mainActiveIndex,event.detail.index)
    this.setData({
      mainActiveIndex: event.detail.index
    })
  },
  food(e) {
    // console.log('点击')
    let index = e.currentTarget.dataset.index
    // console.log(index);
    this.setData({
      select1: index
    })
  },
  click(e) {
    // console.log('点击')
    let index = e.currentTarget.dataset.index
    var popClass
    // console.log(index);
    if (index == "chuye") {
      popClass = 1
    } else {
      popClass = 2
    }
    this.setData({
      select: index,
      popClass: popClass
    })
  },
  //选择日期-时间选择器
  showDate() {
    this.setData({
      topTimeShow: true
    })
  },
  hideDate() {
    this.setData({
      topTimeShow: false
    })
  },
  confirm(value) {
    let topTime = this.toDates(value.detail, 0)
    this.setData({
      topTime,
      topTimeShow: false
    })
  },
  //将时间戳转为日期
  toDates(times, type) {
    const date = new Date(times)
    const Y = date.getFullYear()
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
    const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
    const H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    const Min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    const S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    // const dateTime = Y + '年' + M + '月' + D + '日' + H + '时' + Min + '分' + S + '秒'
    let dateTime
    if (type == 0) {
      dateTime = Y + '年' + M + '月' + D + '日'
    } else if (type == 1) {
      dateTime = M + '月' + D + '日'
    } else if (type == 2) {
      dateTime = +H + ':' + Min
    }
    return dateTime
  },

  // 获取用户手机号权限
  getPhoneNumber(e) {
  
  },

  //记一笔
  showPop() {
    this.setData({
      show:false
    })
    //  获取当前时间戳
    let timestamp = Date.parse(new Date());
    if(wx.getStorageSync("userInfo")==""){
      console.log('执行')
      wx.login({
        success(res) {
          console.log(res);
          if (res.code) {
            //发起网络请求
            console.log(res);
            wx.request({
              url: 'https://server.ifufan.com/Index/index/userLogin',
              data: {
                code: res.code,
                username:"admin",
                password:"admin@123456",
              }
            })
            wx.setStorage({
                key: "userInfo",
                data: res.code
              })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
    this.setData({
      popMl1:'',
      popShow: true,
      popDate: this.toDates(timestamp, 1),
      popTime: this.toDates(timestamp, 2),
      userInfo:wx.getStorageSync("userInfo")
    })
    
  },
  hidePop() {
    this.setData({
      popShow: false
    })
    this.setData({
      userInfo:wx.getStorageSync("userInfo")
    })
  },
  hidePop1() {
    this.setData({
      select1: ''
    })
  },
  hidePop2() {
    this.setData({
      select2: '',
      popMl1: ''
    })
  },
  hidePop3() {
    this.setData({
      select2: ''
    })
  },
  //输入量num
  onChange(e) {
    this.setData({
      popMl: e.detail
    })
  },
  onChange1(e) {
    this.setData({
      popMl1: e.detail
    })
    console.log(popMl1)
  },
  //选择类型
  selectedType(e) {
    const {
      index
    } = e.currentTarget.dataset
    let typelist = this.data.typelist
    typelist.forEach((item, ind) => {
      if (index == ind) {
        item.selected = true
      } else {
        item.selected = false
      }
    })
    this.setData({
      typelist,
      popType: index

    })
  },
  //选择正常量
  selectRank(e) {
    const {
      index
    } = e.currentTarget.dataset
    let typeNumlist = this.data.typeNumlist
    typeNumlist.forEach((item, ind) => {
      if (index == ind) {
        item.selected = true
      } else {
        item.selected = false
      }
    })
    this.setData({
      // popMl:'150',
      typeNumlist,
      popRank: index
    })
  },

  //提交
  async submit() {
    this.setData({
      userInfo:wx.getStorageSync("userInfo")
    })
    let data = {}
    data['flag'] = '/Index/Liquid/create_liquid'
    data['status'] = this.data.popClass
    data['type'] = this.data.popType
    data['content'] = this.data.popRank
    if (this.data.popClass == 2) {
      data['num'] = this.data.popMl1
     if(this.data.xzarr.length>0){
      data['food'] = this.data.xzarr.join(',')
     }
    } else {
      data['num'] = this.data.popMl
    }
    const res = await api.send(data, {
      method: 'POST'
    })
    if (res.code === '200') {
      Toast('提交成功')
      this.getlist()
    } else {}
    this.setData({
      popShow: false,
      // popClass:'',
      popMl1:'',
      // popMl:'',
      xzarr:[],
      xuanze:'',
      xuanze1:'',
      xuanze2:'',
      zhiliang:'',
      zhiliang1:'',
      zhiliang2:'',
    })
  },

  //获取列表
  async getlist() {
    let data = {}
    data['flag'] = '/Index/Liquid/get_liquid_date'
    data['date'] = this.data.topTime
    const res = await api.send(data, {
      method: 'POST'
    })
    if (res.code === '200') {
      this.setData({
        inputNum: res.data.input_num,
        outNum: res.data.out_num,
        inputNumCount: res.data.all_input_num,
        outNumCount: res.data.all_out_num,
        list: res.data.list
      })
    } else {}
  },
  // 获取食物列表
  async getFoodlist() {
    let data = {}
    data['flag'] = '/Index/Liquid/get_food_list'
    var array = []
    for (let i = 1; i < 4; i++) {
      data['type'] = i
      const res = await api.send(data, {
        method: 'POST'
      })
      // console.log(res);
      array.push(res.data)
    }
    // console.log(array)
    this.setData({
      typelist1: array
    })
    // const res = await api.send(data,{method:'POST'})
    // console.log(res.data);
    // if(res.code === '200') {
    //   this.setData({
    //     typelist1:res.data
    //   })
    //   console.log(this.data.typelist1);
    // }else {
    // }
    //     const app = getApp()
    // const HOST = app.baseURL
    // var userid = app.globalData.userid;
    // var date = this.data.topTime
    // console.log(HOST,userid)
    //     wx.request({
    //       url:HOST+ '/Index/Liquid/get_liquid_date',
    //       data: {
    //         type: '水果',
    //         userid:'18',
    //         date:date
    //       },
    //       method:'post',
    //       success (res) {
    //         console.log(res.data)
    //       }
    //     })
  },
  // 获取食物含水量
  async getattribute() {
    let data = {}
    data['flag'] = '/Index/Liquid/count_food_water'
    data['food_attribute_id'] = ''
    const res = await api.send(data, {
      method: 'POST'
    })
    // console.log(res);
    // wx.showModal({
    //   content: JSON.stringify(res)+JSON.stringify(data)
    // })
    if (res.code === '200') {
      this.setData({
        end: res.data
      })
      // console.log(this.data.end);
      // wx.showModal({
      //   title: '提示',
      //   content: JSON.stringify(this.data.end)
      // })
    } else {

    }

  },
  number(e){
    this.setData({
      number:e.detail.value
    })
    // console.log(this.number);
  },
  bed_number(e){
    this.setData({
      bed_number:e.detail.value
    })
    console.log(e.detail.value)
  },
  age(e){
    this.setData({
      age:e.detail.value
    })
    // console.log(e)
  },
  high(e){
    this.setData({
      high:e.detail.value
    })
  },
  weight(e){
    this.setData({
      weight:e.detail.value
    })
    // console.log(e)
  },
  temperature(e){
    this.setData({
      temperature:e.detail.value
    })
  },

  // 获取问卷列表
  async question_list(){
    this.setData({
      show:false
    })
    let data={}
    data['number'] = this.data.number
    data['bed_number']=this.data.bed_number
    data['sex']=this.data.sex
    data['userid']=wx.getStorageSync("userid")
    data['age']=this.data.age
    data['high']=this.data.high
    data['weight']=this.data.weight
    data['temperature']=this.data.temperature
    data['sweat']=this.data.sweat
    data['cut']=this.data.cut
    data['burn']=this.data.burn
    data['create_time']=moment().format('YYYY-MM-DD')
    wx.request({
      url: 'https://server.ifufan.com/Index/Liquid/create_question',
      method: 'POST',
      data: data,
      success(res) {
        console.log(res)
      }
    })
  },
  // 判断用户有没有提交过问卷
  is_one(){
    wx.request({
      url: 'https://server.ifufan.com/Index/Liquid/is_one',
      method: 'POST',
      data:{
        userid:wx.getStorageSync("userid"),
        name:wx.getStorageSync("username"),
      },
      success:(res)=>{
        console.log(res,"结果")
        //重要
        if( res.data.data != -1){
          this.setData({
            show:true
          })
          return
        }
      }
    })
  },

  // 删除信息
  gogo(e){

    console.log(e.target.dataset.num,"===")
    wx.request({
      url: 'https://server.ifufan.com/Index/Liquid/delete_liquid/id',
      data:{
        id:e.target.dataset.num.id
      },
      success:(res)=>{
        console.log(res)
        this.getlist()
      }
    })
  },

  // 跳转信息页面

  gogogo(){
    wx.redirectTo({
      url: '/pages/liquidlog/index',
    })
  },
  gotongji(){
    wx.redirectTo({
      url: '/pages/mygogo/mygogo',
    })
  },
  goindex(){
    wx.redirectTo({
      url: '/pages/mymy/mymy',
    })
  },

  // 获取出液量
  getoutrexor(){
    wx.request({
      url: 'https://server.ifufan.com/Index/Liquid/out_recordio',
      method:"POST",
      data:{
        userid:wx.getStorageSync('userid')
      },
      success:(res)=>{
        console.log(res,'出液')
        this.setData({
          chuye:res.data.data
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.login({
      success:(res)=>{
        console.log(res,"denglu")
        wx.request({
          url: 'https://server.ifufan.com/Index/Wechat_Auth/login',
          method:"POST",
          data:{
            code:res.code
          },
          success:(res)=>{
            console.log(res,"shuju")
            wx.setStorageSync('userid', res.data.data.id)
          }
        })
      }
    })
    this.getlist()
    this.getFoodlist()
    this.getattribute()
   


    
    let clock = new Date(+new Date() + 3600*8 *1000).toISOString().replace(/T/g," ").replace(/\.[\d]{3}Z/,"")
    this.setData({
      clock : clock
    })
    console.log(clock,"shijain")
    let that = this;
    let timestamp = Date.parse(new Date());
    this.setData({
      topTime: this.toDates(timestamp, 0),
      popDate: this.toDates(timestamp, 1),
      popTime: this.toDates(timestamp, 2)
    })
    app.userInfoReadyCallback = res => {
      this.getlist(this.data.topTime)
    }
    // this.onClickShow()
    this.getoutrexor()
    this.is_one() // 是否填写过问卷
    // return
    


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    let arr=[]
    let that=0
    for(var i=10;i<=2000;i+=10){
      that=i+'ml';
      arr.push(that)
    }
    // console.log(arr)
    this.setData({
      columns:arr
    })



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})